#!/usr/bin/env bash

set -e

cd $(dirname $0)

source ./env

if [[ $# -eq 0 ]]; then
	set -- cmd/* schema
fi

version=$(git describe --tags --always --dirty)
version="${version#v}"
version="${version/-/+}"
ldflags="-X ${REPO_PATH}/version.Version=${version}"
schema_generate() {
    export GOBIN="../tools/bin"
    mkdir -p ${GOBIN}
    if [ ! -x "${GOBIN}/schematyper" ]; then
        (
            echo "Building schematyper"
            cd schematyper &&
                go build -mod vendor -o "${GOBIN}/schematyper" .
        )
    fi

    schema_version="v1"
    schema_json="../src/schema/${schema_version}.json"
    echo "Generating COSA Schema ${schema_version}"

    out="cosa/cosa_${schema_version}.go"
    "${GOBIN}/schematyper" \
        "../src/schema/${schema_version}.json" \
        -o "${out}.tmp" \
        --package="cosa" \
        --root-type=Build \
        --ptr-for-omit
    # Avoid having a filename in generated code since it
    # can vary depending on local checkout paths.
    sed -e s,'^// generated by "\(/.*\)/schematyper\(.*\)$,// generated by "schematyper\2,' < "${out}.tmp" > "${out}".tmp2
    rm -f "${out}.tmp"
    mv "${out}"{.tmp2,}

    cat > "cosa/schema_doc.go.tmp" <<EOM
// Generated by ${0}
// DO NOT EDIT

package cosa

var generatedSchemaJSON = \`$(< ${schema_json})
\`
EOM
    mv cosa/schema_doc.go{.tmp,}
}

host_build() {
	local cmd=$1; shift
	echo "Building $cmd"
	go build -i \
		-ldflags "${ldflags}" \
		-mod vendor \
		-o "bin/$cmd" \
		"$@" "${REPO_PATH}/cmd/$cmd"
}

host_static_build() {
	local cmd=$1; shift
	echo "Building $cmd (static)"
	go build \
		-ldflags "${ldflags} -extldflags=-static" \
		-mod vendor \
		-o "bin/$cmd" \
		-tags osusergo,netgo \
		"${REPO_PATH}/cmd/$cmd"
}

# Unused now, but kept in case we want it in the future
cross_build() {
	local a
	for a in amd64 arm64 s390x ppc64le; do
		echo "Building $a/$1"
		mkdir -p "bin/$a"
		CGO_ENABLED=0 GOARCH=$a \
			go build -mod=vendor -ldflags "${ldflags}" \
			-o "bin/$a/$1" "${REPO_PATH}/cmd/$1"
	done
}

for arg in "$@"; do
	if [ "${arg}" = "schema" ]; then
		schema_generate
	else
		cmd=$(basename "${arg}")
		if [ "${cmd}" = "kolet" ]; then
			host_static_build kolet
		else
			host_build "${cmd}"
		fi
	fi
done
